$(function(){
    var $orderList = $("#orderList");
    var $orderItem = $(".js-order-item");
    var $numberIpt = $orderItem.find(".js-number-input");
    var $shopsCheck = $orderItem.find(".js-shops-check");
    var $goodsCheck = $orderItem.find(".js-goods-check");
    var $checkAll = $("#checkAll");



    $(document).on("click", ".js-goods-cart", function(e){
        var $target = $(e.target);

        if($target.hasClass("js-number-sub")){
            NumberSub($target);
        }
        else if($target.hasClass("js-number-plus")){
            NumberPlus($target);
        }
        else if($target.hasClass("js-remove-btn")){
            RemoveGoods($target);
        }
    });

    $numberIpt.on("input propertychange", function(){
        var $this = $(this);

        OptionIpt($this);
    });

    $numberIpt.on("keyup", function(){
        var val = parseInt(this.value);

        if (isNaN(val) || val <= 0) {
            val = 1;
        }
        if (this.value != val) {
            this.value = val;
        }
    });
	
	$numberIpt.trigger("input");//初始化

    $(document).on("click", "#cartNav", function(e){
        var $target = $(e.target);

        if($target.hasClass("js-remove-all")){
            RemoveSelected();
        }
        else if($target.hasClass("js-settle-accounts")){
            SettleAccounts();
        }
    });

    //商家选择
    $shopsCheck.on("click", function(){
        var $this = $(this);
        var $goodsCheck = $this.closest(".js-order-item").find(".js-goods-check");
        var $shopsCheck = $orderList.find(".js-shops-check");
        var $checked = $orderList.find(".js-shops-check:checked");

        CheckAll($this, $goodsCheck);
        CheckSingle($this, $shopsCheck, $checked, $checkAll);
    });

    //商品选择
    $goodsCheck.on("click", function(){
        var $this = $(this);
        var $goodsCheck = $this.closest(".js-order-item").find(".js-goods-check");
        var $checked = $this.closest(".js-order-item").find(".js-goods-check:checked");
        var $shopsCheck = $this.closest(".js-order-item").find(".js-shops-check");
        
        var $goodsCheck2 = $orderList.find(".js-goods-check");
        var $checked2 = $orderList.find(".js-goods-check:checked");
        
        CheckSingle($this, $goodsCheck, $checked, $shopsCheck);
        CheckSingle($this, $goodsCheck2, $checked2, $checkAll);
    });

    //全选
    $checkAll.on("click", function(){
        var $this = $(this);
        var $shopsCheck = $(".js-order-item").find(".js-shops-check");
        
        CheckAll($this, $shopsCheck);
    });
});

//数量减
function NumberSub(element){
    var $parent = element.closest(".js-goods-cart");
    var $ipt = $parent.find(".js-number-input");
    var iptValue = parseInt($ipt.val());
    var cartId = $parent.attr("cartId");

    if(!isNaN(iptValue)){
        iptValue--;
        if(iptValue <= 1){
            iptValue = 1;
            element.addClass("mallui_number-disabled");
        }
        $ipt.val(iptValue);

        cartNumUpdate(cartId,iptValue);
    }

    getSubtotal($parent);
    getTotal(); //更新合计
}

//数量加
function NumberPlus(element){
    var $parent = element.closest(".js-goods-cart");
    var $ipt = $parent.find(".js-number-input");
    var $subElement = $parent.find(".js-number-sub");
    var iptValue = parseInt($ipt.val());
    var cartId = $parent.attr("cartId");

    if(!isNaN(iptValue)){
        iptValue++;
        $ipt.val(iptValue);
        $subElement.removeClass("mallui_number-disabled");

        cartNumUpdate(cartId,iptValue);
    }

    getSubtotal($parent);
    getTotal(); //更新合计
}

//操作数量输入框
function OptionIpt(input){
    var $subElement = input.prev(".js-number-sub");
    var $parent = input.closest(".js-goods-cart");
    var iptValue = parseInt(input.val());
    var cartId = $parent.attr("cartId");

    if(!isNaN(iptValue)){
        if(iptValue < 1) {
            input.val(1);
            $subElement.addClass("mallui_number-disabled");

            cartNumUpdate(cartId,1);
        }
        else if(iptValue == 1){
            $subElement.addClass("mallui_number-disabled");

            cartNumUpdate(cartId,1);
        }
        else{
            $subElement.removeClass("mallui_number-disabled");

            cartNumUpdate(cartId,iptValue);
        }
    }

    getSubtotal($parent);
    getTotal(); //更新合计
}

//更新购物车数量
function cartNumUpdate(cartId,iptValue){
    $.ajax({
        url: "cartNumUpdate",
        type: "post",
        dataType: 'json',
        data: {
            cartId: cartId,
            count: iptValue
        },
        success: function(){
            
        },
        error: function(xhr, type, errorThrown) {
            //异常处理；
            alert("请稍后再试！");
        }
    });
}

//删除当前商品
function RemoveGoods(element){
    var $parent = element.closest(".js-goods-cart");
    var cartId = $parent.attr("cartid");

    if(confirm("该商品挺抢手，确认删除吗?")){
        $parent.remove();
        getTotal(); //更新合计
        var ids = [];
        ids.push(cartId);
        $.ajax({
            url: "delCart",
            type: "post",
            dataType: 'json',
            data: {
                ids:JSON.stringify(ids)
            },
            success: function(){
                var len = $(".js-order-item").find(".js-goods-cart").length;

                if(len === 0){
                    location.href = "emptyCart";
                }
                
                //cartCnt(); //重新计算购物车数量
            },
            error: function(xhr, type, errorThrown) {
                //异常处理；
                alert("请稍后再试！");
            }
        });
    }   
}

//全选
function CheckAll(all, item){
    var $orderItem = $(".js-order-item");

    if(all.prop("checked")){
        item.prop("checked", true);
        $orderItem.find(".js-goods-check").prop("checked", true);
    }
    else{
        item.prop("checked", false);
        $orderItem.find(".js-goods-check").prop("checked", false);
    }

    $orderItem.find(".js-goods-cart").each(function() {
        getSubtotal($(this));
    });
    getTotal(); //更新合计
}

//单选
function CheckSingle(ele, item, itemChecked, all){
    var $parent = ele.closest(".js-goods-cart");
    var len = item.length;
    var checkedLen = itemChecked.length;
    
    if(checkedLen == len){
      all.prop("checked", true);
    }
    else{
      all.prop("checked", false);
    }

    getSubtotal($parent);
    getTotal(); //更新合计
}


//删除选中
function RemoveSelected(){
    var $orderItem = $(".js-order-item");
    var checkedLen = $orderItem.find(".js-goods-check:checked").length;
    if(checkedLen > 0){
        if(confirm("勾选商品挺抢手，确认删除吗?")){
            var ids = [];
            $(".js-order-item").find(".js-goods-check:checked").each(function(){
                var _this = $(this);
                ids.push(_this.val());
                _this.closest(".js-goods-cart").remove();
            });
            getTotal(); //更新合计
            $.ajax({
                url: "delCart",
                type: "post",
                dataType: 'json',
                data: {
                    ids: JSON.stringify(ids)
                },
                success: function(){
                    var len = $(".js-order-item").find(".js-goods-cart").length;

                    if(len === 0){
                        location.href = "emptyCart";
                    }
                    
                    //cartCnt(); //重新计算购物车数量
                },
                error: function(xhr, type, errorThrown) {
                    //异常处理；
                    alert("请稍后再试！");
                }
            });
        }
    }
                
}

//计算单行价格
function getSubtotal(parent){
    var unitPrice = parseFloat(parent.find(".js-unit-price").text());
    var num = parseInt(parent.find(".js-number-input").val()) || 1;
    var subtotal = 0;

    subtotal = parseInt(num) * parseFloat(unitPrice).toFixed(2);
    //console.log(subtotal);

    parent.data("subtotal", subtotal);

    var $sumPrice = parent.find(".js-unit-sumPrice");
    $sumPrice.text(subtotal.toFixed(2));
}

//更新合计
function getTotal(){
    var $settleAccounts = $("#settleAccounts");
    var $totalPrice = $("#totalPrice");
    var total = 0;
    //var freight = Number($("#logisticsPrice").val()); //运费
    var freight = 0;
    var $totalGoods = $("#totalGoods");
    var sumGoods=0;

    $(".js-order-item").find(".js-goods-check").each(function(){
        if(this.checked){
            var subtotal = $(this).closest(".js-goods-cart").data("subtotal") || 0;
            // console.log(subtotal);
            sumGoods +=1;
            total += subtotal;
            // console.log(total);
            $settleAccounts.addClass("mallui_btn_enable");
			$settleAccounts.prop("disabled", false);
        }
    });
    if(total == 0){
        $settleAccounts.removeClass("mallui_btn_enable");
		$settleAccounts.prop("disabled", true);
    }
    else{
        total = total + freight;
    }
    $totalPrice.text(total.toFixed(2));
    $totalGoods.text(sumGoods);
}

//结算
function SettleAccounts(){
	var goodsItemIds = "";
	var counts = "";
	var cartIds = "";

    $(".js-order-item").find(".js-goods-check:checked").each(function(){
		var _this = $(this);
		var goodsItem = _this.closest(".js-goods-cart");
		var number = parseInt(goodsItem.find(".js-number-input").val());
		var id = goodsItem.attr("id");
		var cartId = _this.val();

		if(!isNaN(number)){
            counts += number + ",";
        }
        else{
            layer.open({
                content: '请输入商品数量',
                scrollbar: false
            });
            return false;
        }
		goodsItemIds += id + ",";
		cartIds += cartId + ",";
	});
	
	if( cartIds.length > 0 ){
		cartIds = cartIds.substring(0,cartIds.lastIndexOf(","));
		sessionStorage.setItem("cartIds", cartIds);
	}
	
	if( goodsItemIds.length > 0 && counts.length > 0 ){
		goodsItemIds = goodsItemIds.substring(0,goodsItemIds.lastIndexOf(","));
		counts = counts.substring(0,counts.lastIndexOf(","));
		location.href = "orderConfirm?goodsItemIds=" + goodsItemIds + "&counts=" + counts;
	}else{
        layer.open({
            content: '请选择商品',
            scrollbar: false
        });
    }
}